import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate';  
Vue.use(Vuex);
import {
	getphoneModel
} from '@/api/user.js'
import {
	getTrolleyList,
	addTrolley,
	getAddressList,
	getAreaOptions
} from '@/api/product.js'
const store = new Vuex.Store({
	state: {
		exampleMaterial: {},
		productMaterial: {},
		myCustomMaterial: {},
		token: '',
		userInfo: {},
		avatar: '',
		code: '',
		phoneModelId: '',
		phoneModelName: '',
		phoneNumber: '',
		phoneModelList: [],
		trolleyList: {
			invalidList: [],
			validList: []
		},
		addressList: [], //  地址列表
		defaultAddress: {}, //  默认地址
		areaOptions: [], //  地区选项
		showPrivacy: false, //是否授权隐私协议
		messages: {}, //  存储消息
		totalCredits: 0, //  总积分
		isStore:'', //  是否有商店
		currentMaterial: {} //  当前选择的材质
	},
	getters: {
		token(state) {
			return state.token
		},
		userInfo(state) {
			return state.userInfo
		},
		avatar(state) {
			return state.avatar
		},
		code(state) {
			return state.code
		},
		phoneModelId(state) {
			return state.phoneModelId
		},
		phoneModelName(state) {
			return state.phoneModelName
		},
		phoneNumber(state) {
			return state.phoneNumber
		},
		// 购物车列表
		trolleyList(state) {
			return state.trolleyList
		},
		// 购物车总商品数、总金额
		trolleySum(state) {
			let amount = 0 //  定义一个变量amount，初始值为0
			let count = 0
			let selectCount = 0
			state.trolleyList.validList.forEach((item) => { //  遍历购物车列表中的有效商品
				count += Number(item.quantity) //  将商品数量转换为数字并累加到count变量中
				if (item.selected == true) { //  如果商品被选中
					amount += Number(item.price) * Number(item.quantity)
					selectCount += Number(item.quantity)
				}
			})
			let sum = {
				productCount: selectCount,
				productAmount: amount / 100,
				allCount: count,
			}
			return sum
		},
		// 收货地址列表
		addressList(state) {
			return state.addressList
		},
		// 默认收货地址
		defaultAddress(state) {
			return state.defaultAddress
		},
		phoneModelList(state) { //  根据state获取手机型号列表
			return state.phoneModelList
		},
		areaOptions(state) { //  根据传入的state参数，返回一个区域选项
			return state.areaOptions
		},
		showPrivacy(state) { //  显示隐私设置
			return state.showPrivacy
		},
		messages(state) { //  获取state中的messages
			return state.messages
		},
		totalCredits(state) { //  计算总学分
			return state.totalCredits
		},
		isStore(state) { //  判断是否为商店
			return state.isStore
		},
		getCurrentMaterial(state){//  返回当前选择的材质
			return state.currentMaterial 
		},
		getExampleMaterial: state => state.exampleMaterial,
		getProductMaterial: state => state.productMaterial,
		getMyCustomMaterial: state => state.myCustomMaterial,
	},
	mutations: {
		setTOken(state, token) { //  设置token
			state.token = token
		},
		setUserInfo(state, userInfo) { //  设置用户信息
			state.userInfo = userInfo //  将用户信息赋值给state中的userInfo
			state.avatar = userInfo.avatar //  将用户信息中的avatar赋值给state中的avatar
			state.code = userInfo.code //  将用户信息中的code赋值给state中的code
			state.phoneModelId = userInfo.phoneModelId //  将用户信息中的phoneModelId赋值给state中的phoneModelId
			state.phoneModelName = userInfo.phoneModelName //  将用户信息中的phoneModelName赋值给state中的phoneModelName
			state.phoneNumber = userInfo.phoneNumber //  将用户信息中的phoneNumber赋值给state中的phoneNumber
		},
		setAvatar(state, avatar) { //  设置头像
			state.avatar = avatar //  将传入的avatar参数赋值给state中的avatar属性
		},
		setCode(state, code) { //  设置代码
			state.code = code
		},
		setPhoneModelId(state, phoneModelId) { //  设置手机型号ID
			// if (state.phoneModelId === phoneModelId) return // 值相同不更新
			state.phoneModelId = phoneModelId //  将传入的手机型号ID赋值给state中的phoneModelId
		},
		setPhoneModelName(state, phoneModelName) { //  设置手机型号名称
			state.phoneModelName = phoneModelName //  将传入的手机型号名称赋值给state中的phoneModelName属性
		},
		setPhoneNumber(state, phoneNumber) { //  设置电话号码
			state.phoneNumber = phoneNumber //  将传入的电话号码赋值给state中的phoneNumber属性
		},
		setTrolley(state, trolleyList) { //  设置购物车列表
			state.trolleyList = trolleyList //  将传入的购物车列表赋值给state中的trolleyList
		},
		setProduct(state, product) { //  设置产品

		},
		getAddressList(state, addressList) { //  获取地址列表
			state.addressList = addressList
			// 设置默认地址
			state.defaultAddress = addressList.filter(item => {
				return item.defaultAddress
			})[0] || {}
		},
		async setPhoneModelList(state, phoneModelList) { //  异步设置手机型号列表
			// await new Promise((resolve) => {
			// 	getphoneModel().then(res => {
			// 		state.phoneModelList = res.data
			// 		resolve()
			// 	})
			// })
			state.phoneModelList = phoneModelList
		},
		setAreaOptions(state, areaOptions) { //  设置区域选项
			state.areaOptions = areaOptions
		},
		steShowPrivacy(state, data) { //  显示隐私设置
			state.showPrivacy = data
		},
		setMessages(state, data) {
			state.messages = data
		},
		setTotalCredits(state, data) {
			state.totalCredits = data //  将data赋值给state中的totalCredits属性
		},
		
		setIsStore(state, data) {
			state.isStore = data //  设置state中的isStore属性为data的值
		},
		setCurrentMaterial(state, data){//  设置当前选择的材质
			if (!data?.materialMap?.[10]) {
				console.error('Invalid material data:', data)
				return
			}
			state.currentMaterial = data //  将传入的data赋值给state中的currentMaterial属性

		},
		setExampleMaterial(state, payload) {
			state.exampleMaterial = payload || {}
		},
		setProductMaterial(state, payload) {
			state.productMaterial = payload || {}
		},
		setMyCustomMaterial(state, payload) {
			state.myCustomMaterial = payload || {}
		},
	},
	actions: {
		getTrolley(context, data) { //  获取购物车
			getTrolleyList().then(res => {
				context.commit('setTrolley', res.data)
			})
		},
		// 添加删除商品
		setProduct(context, {
			phoneCaseId,
			quantity
		}) {
			let postProdut = {
				phoneCaseId: phoneCaseId,
				quantity: quantity
			}
			addTrolley(postProdut).then(res => {
				uni.$u.debounce(() => {
					context.dispatch('getTrolley')
				})
			})
		},
		// 获取收货地址列表
		async getAddressList(context, data) {
			return new Promise((resolve) => {
				getAddressList({ //  获取地址列表
					pageSize: 10
				}).then(res => {
					context.commit('getAddressList', res.data)
					resolve()
				})
			})

		},
		// 获取地域列表
		getAreaOptions(context, data) {
			if (context.state.areaOptions.length == 0) {
				getAreaOptions().then(res => {
					context.commit('setAreaOptions', res.data)
				})
			}

		},
		// 获取机型列表
		setPhoneModelList(context, data) {
			getphoneModel().then(res => {
				context.commit('setPhoneModelList', res.data) //  提交mutation，将res.data作为参数传递给setPhoneModelList
			})
		}

	},
	plugins: [createPersistedState({
		// exampleMaterial: {},
		// productMaterial: {},
		// myCustomMaterial: {},
		paths: ['currentMaterial', 'phoneModelId','exampleMaterial','productMaterial','myCustomMaterial'], // 明确指定需要持久化的字段
		storage: {
		  getItem: key => wx.getStorageSync(key),
		  setItem: (key, value) => wx.setStorageSync(key, value),
		  removeItem: key => wx.removeStorageSync(key)
		}
	  })],
})
export default store